package top.ajunnihao.core.util.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义普通异常处理器
 */
public class CommonExceptionResolver implements HandlerExceptionResolver {

    /**
     * 日志记录
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         Object o,
                                         Exception e) {
        logger.error("Request URL : {}, Exception : {}", httpServletRequest.getRequestURL(), e.getMessage());

        // 获取异常对象，如果是自定义异常类型则强转，否则创建一个
        CommonException ex;
        if (e instanceof CommonException) {
            ex = (CommonException) e;
        } else {
            ex = new CommonException("系统正在维护...");
        }

        // 创建 ModelAndView 对象，将异常提示信息存进去，跳转到异常页面
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", httpServletRequest.getRequestURL());
        mv.addObject("exception", ex);
        mv.setViewName("error/error");
        return mv;
    }

}
